package com.ht.modules.system.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ht.entity.LoginUser;
import com.ht.modules.system.entity.SysLoginError;
import com.ht.modules.system.entity.SysLoginErrorVo;
import com.ht.modules.system.mapper.SysLoginErrorMapper;
import com.ht.modules.system.service.ISysLoginErrorService;
import com.ht.utils.DicConstants;
import com.ht.utils.RedisUtil;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * 登录错误表
 */
@Service
public class SysLoginErrorServiceImpl extends ServiceImpl<SysLoginErrorMapper, SysLoginError> implements ISysLoginErrorService {

    @Autowired
    private SysLoginErrorMapper sysLoginErrorMapper;
    @Autowired
    private RedisUtil redisUtil;

    @Override
    public Page<SysLoginErrorVo> list(Page<SysLoginErrorVo> page, SysLoginErrorVo sysLoginErrorVo) {
        return page.setRecords(sysLoginErrorMapper.list(page, sysLoginErrorVo));
    }

    @Override
    public void add(String ipAddress, String username) {
        SysLoginError sysLoginError = new SysLoginError();
        sysLoginError.setIp(ipAddress);
        sysLoginError.setUsername(username);
        sysLoginError.setBannedState(DicConstants.LOGIN_BANNED_STATE_YFJ);
        this.save(sysLoginError);
    }

    @Override
    public SysLoginError queryById(String id) {
        SysLoginError sysLoginError = this.getById(id);
        if (sysLoginError == null) {
            throw new RuntimeException("未找到对应实体！");
        }
        return sysLoginError;
    }

    @Override
    public void unsealBatch(String ids, String unsealReason) {
        if (ids == null || ids.trim().isEmpty()) {
            throw new RuntimeException("参数不识别！");
        }
        String[] idsArray = ids.split(",");
        // 根据ids找到要解封的ip和用户名（24小时内的，因为redis只存了24小时）
        List<Map<String, String>> needUnsealList = sysLoginErrorMapper.getNeedUnsealListByIds(idsArray);
        if (needUnsealList == null || needUnsealList.isEmpty()) {
            throw new RuntimeException("未找到24小时内可解封记录！");
        }
        for (Map<String, String> needUnsealMap : needUnsealList) {
            String ip = needUnsealMap.get("ip");
            String username = needUnsealMap.get("username");
            redisUtil.del(DicConstants.LOGIN_ERROR_TIME + ip + username);
        }
        // 获取当前用户
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        // 更新登录异常日志
        sysLoginErrorMapper.unsealBatch(DicConstants.LOGIN_BANNED_STATE_YJF,
                sysUser.getId(), unsealReason, idsArray);
    }

}
